package com.example.seakdreamandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.Result;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.playHistory.PlayHistoryActivity;
import com.example.seakdreamandroid.sleep.AlarmClockAndPrompt;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MusicStoryPlayerActivity extends AppCompatActivity {

    private SeekBar sb_normal;
    private Context mContext;
    private ImageButton play;
    private ImageButton replay;
    private ImageButton list;
    private ImageButton clock;
    private ImageButton favorite;
    private Intent intentToFavorite, intentToClock, intentC, intentToHistory;
    private MusicPic musicPic;
    private Boolean isFavorite = false;
    private ImageButton returnF2;
    TextView textView,  textView2;
    MyConnection myConnection;
    MSPService.Finder controller;
    private boolean isPlay = true;
    private Timer timer;
    private Timer timer2;
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            //时间到停止播放
            Message message = new Message();
            message.what = 7;
            handler.sendMessage(message);
        }
    };
    User user;

    public Handler handler = new Handler(Looper.getMainLooper()){
        public void handleMessage(Message message){//实时更新进度条
            super.handleMessage(message);
            int msg = message.what;
            switch (msg){
                case 7:
                    musicPic.playMusic();
                    isPlay = false;
                    controller.playM();
                    play.setBackgroundResource(R.mipmap.msppause);
                    break;
                case 1:
                    //点击喜欢后修改图片状态
                    if (isFavorite){
                        favorite.setBackgroundResource(R.mipmap.like2);
                    }else{
                        favorite.setBackgroundResource(R.mipmap.nolike);
                    }
                    break;
                case 2:
                    //更新进度条，单位秒,同时检查白噪音是否在播放，检查是否要求音乐关闭，user.isEnd()，是则关闭此播放器，
                    int progress = controller.getCurrentPosition();
                    sb_normal.setProgress(progress);
                    textView.setText(formatTime(progress));
                    if (user.isWhiteNoiseIsPlay() || user.isEnd()){
                        controller.pause();
                        isPlay = false;
                        musicPic.pauseMusic();
                        play.setBackgroundResource(R.mipmap.msppause);
                        user.setEnd(false);
                    }
                    break;
                case 3:
                    //音乐准备完成
                    int duration = controller.getDuration();//获取音乐总时长
                    textView2.setText(formatTime(duration));//设置总时长
                    sb_normal.setMax(duration);//设置进度条的最大值
                    musicPic.playMusic();
                    play.setEnabled(true);
                    sb_normal.setEnabled(true);
                    play.setBackgroundResource(R.mipmap.mspplay);
                    isPlay = true;
                    addTimer();
                    break;
            }
        }
    };

    private void addTimer() {
        if(timer != null){
            timer.cancel();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(isPlaying()){
                    handler.sendEmptyMessage(2);
                }
            }
        },0,500);
    }
    public boolean isPlaying(){
        return isPlay;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        user.setMSPIsPlay(false);
        handler.removeMessages(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String formatTime(int length)//时间转化
    {
        Date date=new Date(length);
        SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
        String totalTime=sdf.format(date);
        return totalTime;
    }

    @Override
    protected void onNewIntent(Intent intentC) {
        user.setWhiteNoiseIsPlay(false);
        user.setMSPIsPlay(true);
        WhiteNoisePlayerService.getController().cancelAutoPlay();
        if(WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING){
            WhiteNoisePlayerService.getController().pausePlay(true);
        }
        this.intentC = intentC;
        freshUser();
        if (intentC.getStringExtra("audioUrl") == null){
            Log.i("返回", "单纯跳转");
        }else if (!controller.getUri().equals(intentC.getStringExtra("audioUrl"))){
            if(timer != null)timer.cancel();
            Log.i("返回", intentC.getStringExtra("audioId"));
            new Thread() {
                @Override
                public void run() {
                    //这里写入子线程需要做的工作
                    deleteHistory(intentC.getStringExtra("audioId"));
                    queryFavorite(intentC.getStringExtra("audioId"));
                }
            }.start();
            try {
                controller.setUri(intentC.getStringExtra("audioUrl"));
                textView.setText("00:00");
                textView2.setText("00:00");
                sb_normal.setMax(0);
                sb_normal.setProgress(0);
                play.setBackgroundResource(R.mipmap.msppause);
                sb_normal.setEnabled(false);
                play.setEnabled(false);
                musicPic.stopMusic();
                isPlay = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            if(musicPic.state == MusicPic.STATE_PAUSE){
                musicPic.playMusic();
                isPlay = true;
                play.setBackgroundResource(R.mipmap.mspplay);
                controller.playM();
                user.setMSPIsPlay(true);
            }
        }
        super.onNewIntent(intentC);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_story_player);
        user = (User) getApplication();
        user.setWhiteNoiseIsPlay(false);
        user.setMSPIsPlay(true);
        WhiteNoisePlayerService.getController().cancelAutoPlay();
        if(WhiteNoisePlayerService.getPlayState() == WhiteNoisePlayerService.PLAYING){
            WhiteNoisePlayerService.getController().pausePlay(true);
        }
        mContext = MusicStoryPlayerActivity.this;
        getView();
        bindViews();
        setListener();
        play.setBackgroundResource(R.mipmap.msppause);
        play.setEnabled(false);
        sb_normal.setEnabled(false);
        isPlay = false;
        Intent intent = new Intent(this, MSPService.class);
        intent.putExtra("audioUrl", intentC.getStringExtra("audioUrl"));
        myConnection = new MyConnection();//建立新连接对象
        bindService(intent,myConnection,BIND_AUTO_CREATE);//建立和service连接
    }

    private void freshUser(){
        user.setAudioId(intentC.getStringExtra("audioId"));
        user.setAudioUrl(intentC.getStringExtra("audioUrl"));
        user.setAudioName(intentC.getStringExtra("audioName"));
        user.setAudioAuthor(intentC.getStringExtra("audioAuthor"));
    }

    private void addHistory(String audioId){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("userId", user.getUserId())
                .add("audioId", audioId)
                .add("listenTime", dateFormat.format(date))
                .build();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "History/createHistory")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("返回", "添加成功");
                Log.i("返回", dateFormat.format(date));
            }
        });
    }

    private void addFavorite(String audioId){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("userId", user.getUserId())
                .add("audioId", audioId)
                .add("collectTime", dateFormat.format(date))
                .add("audioName", intentC.getStringExtra("audioName"))
                .add("audioAuthor", intentC.getStringExtra("audioAuthor"))
                .build();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "Favorite/createFavorite")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.i("返回", "添加成功");
                isFavorite = true;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    private void deleteHistory(String audioId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "History/deleteHistory?userId=" + user.getUserId() + "&audioId=" + audioId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("返回", "删除旧的历史记录");
                addHistory(audioId);
            }
        });
    }

    private void queryFavorite(String audioId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/queryFavorite?userId=" + user.getUserId())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Gson gson = new Gson();
                Result result = gson.fromJson(str, new TypeToken<Result<List<AudioInfo>>>(){}.getType());
                List<AudioInfo> audioInfo = (List<AudioInfo>) result.getData();
                int i = 0;
                while (i < audioInfo.size()){
                    if (audioInfo.get(i).getAudioId().equals(audioId)){
                        isFavorite = true;
                        break;
                    }else{
                        isFavorite = false;
                    }
                    i++;
                }
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    private void deleteFavorite(String audioId){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "Favorite/deleteFavorite?userId=" + user.getUserId() + "&audioId=" + audioId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("返回", "取消收藏");
                isFavorite = false;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    private void bindViews() {
        sb_normal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress=seekBar.getProgress();//获取当前进度条位置
                textView.setText(formatTime(progress));
                if(progress == seekBar.getMax() && !controller.isLooping()){
                    play.setBackgroundResource(R.mipmap.msppause);
                    isPlay = false;
                    musicPic.stopMusic();
                }
                seekBar.setProgress(progress);//更新进度条
                controller.setProgress(progress);//更新音乐进度
            }
        });
    }

    private void getView(){
        sb_normal = (SeekBar) findViewById(R.id.seekbar);
        ButtonUtils.addClickScale(play, 0.9f, 150);
        play = findViewById(R.id.play);
        textView = findViewById(R.id.time_now);
        textView2 = findViewById(R.id.time_all);
        replay = findViewById(R.id.replay);
        list = findViewById(R.id.list);
        musicPic = findViewById(R.id.music_pic);
        clock = findViewById(R.id.clock);
        favorite = findViewById(R.id.favorite);
        intentC = getIntent();
        freshUser();
        returnF2 = findViewById(R.id.return_f2);
        new Thread() {
            @Override
            public void run() {
                //这里写入子线程需要做的工作
                deleteHistory(intentC.getStringExtra("audioId"));
                queryFavorite(intentC.getStringExtra("audioId"));
            }
        }.start();
    }

    private void setListener() {
        MyListener listener = new MyListener();
        play.setOnClickListener(listener);
        replay.setOnClickListener(listener);
        list.setOnClickListener(listener);
        clock.setOnClickListener(listener);
        favorite.setOnClickListener(listener);
        returnF2.setOnClickListener(listener);
    }

    private void showDialog() {
        timer2 = new Timer();
        timerTask.cancel();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                //时间到停止播放
                if (isPlay){
                    Message message = new Message();
                    message.what = 7;
                    handler.sendMessage(message);
                }
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(MusicStoryPlayerActivity.this);
        builder.setTitle("选择定时播放的时长(分钟)");
        // 指定下拉列表的显示数据
        final String[] times = { "5", "15", "30", "45", "60" };
        // 设置一个下拉的列表选择项
        builder.setItems(times, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isPlay){
                    Toast.makeText(MusicStoryPlayerActivity.this, "选择的时间为：" + times[which], Toast.LENGTH_SHORT).show();
                    timer2.schedule(timerTask , Integer.parseInt(times[which]) * 60 * 1000);
                }else{
                    Toast.makeText(MusicStoryPlayerActivity.this, "当前没有在播放", Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.show();
    }

    private void getAudio(String id){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/findAudioInfoById?audioId=" + id)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject result = new JSONObject(str);
                    JSONObject favorite = result.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.play:
                    musicPic.playMusic();
                    if (isPlay == false){
                        isPlay = true;
                        user.setMSPIsPlay(true);
                        play.setBackgroundResource(R.mipmap.mspplay);
                    }else{
                        isPlay = false;
                        play.setBackgroundResource(R.mipmap.msppause);
                    }
                    controller.playM();
                    break;
                case R.id.replay:
                    if (controller.isLooping()){
                        controller.setLooping(false);
                        replay.setBackgroundResource(R.mipmap.replaypic);
                    }else{
                        controller.setLooping(true);
                        replay.setBackgroundResource(R.mipmap.alreplaypic);
                    }
                    break;
                case R.id.list:
//                    intentToFavorite = new Intent();
//                    intentToFavorite.setClass(MusicStoryPlayerActivity.this, FavoriteActivity.class);
//                    startActivity(intentToFavorite);
                    intentToHistory = new Intent();
                    intentToHistory.setClass(MusicStoryPlayerActivity.this, PlayHistoryActivity.class);
                    startActivity(intentToHistory);
                    break;
                case R.id.clock:
                    showDialog();
//                    intentToClock = new Intent();
//                    intentToClock.setClass(MusicStoryPlayerActivity.this, AlarmClockAndPrompt.class);
//                    startActivity(intentToClock);
                    break;
                case R.id.favorite:
                    if (!isFavorite){
                        addFavorite(intentC.getStringExtra("audioId"));
                    }else{
                        deleteFavorite(intentC.getStringExtra("audioId"));
                    }
                    break;
                case R.id.return_f2:
                    moveTaskToBack(true);
                    overridePendingTransition(R.anim.down, R.anim.up);
                    break;
            }
        }
    }

    class MyConnection implements ServiceConnection {//控制连接实现mediaPlay的调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            controller= (MSPService.Finder) service;//获取控制连接对象
            controller.service.setActivity(MusicStoryPlayerActivity.this);
            try {
                controller.setUri(intentC.getStringExtra("audioUrl"));
            } catch (Exception e) {
                e.printStackTrace();
            }
//            if (!controller.getUri().equals(intentC.getStringExtra("audioUrl"))){
//                try {
//                    controller.setUri(intentC.getStringExtra("audioUrl"));
//                    int duration = controller.getDuration();//获取音乐总时长
//                    textView2.setText(formatTime(duration));//设置总时长
//                    sb_normal.setMax(duration);//设置进度条的最大值
//                    Update();//提醒进度条更新
//                    musicPic.playMusic();
//                    controller.playM();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }else{
//                if (!controller.isStart()){
//                    int duration = controller.getDuration();//获取音乐总时长
//                    textView2.setText(formatTime(duration));//设置总时长
//                    sb_normal.setMax(duration);//设置进度条的最大值
//                    Update();//提醒进度条更新
//                    musicPic.playMusic();
//                    controller.playM();
//                }else{
//                    int duration = controller.getDuration();//获取音乐总时长
//                    textView2.setText(formatTime(duration));//设置总时长
//                    sb_normal.setMax(duration);//设置进度条的最大值
//                    Update();//提醒进度条更新
//                    musicPic.playMusic();
//                }
//            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}